package com.example.demo.controller;


import com.example.demo.enity.User;
import com.example.demo.service.UserAuthorityService;
import com.example.demo.service.UserService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class UserListOperationController {


    public static String new_password;


    @Autowired
    UserService userService;

    @Autowired
    UserAuthorityService userAuthorityService;

    @GetMapping("/userList")
    public String userList(Model model, HttpServletRequest request) {

        String username = LoginExitController.username;
        model.addAttribute("username", username);

        List<User> users = userService.selectUserList();
        model.addAttribute("users", users);


//        HttpSession session = request.getSession();
//        User user = (User) session.getAttribute("user");
//        Integer value = user.getValue();
//        if (value.equals(1)) {
//            model.addAttribute("value", "1");
//        } else {
//            model.addAttribute("value", "0");
//        }

        return "userList";


    }

    @GetMapping("/searchUserName")
    public String searchUserName(User user, Model model) {

//
//        HttpSession session = request.getSession();
//        User sessionUser = (User) session.getAttribute("user");
//        Integer value = sessionUser.getValue();
//        if (value.equals(1)) {
//            model.addAttribute("value", "1");
//        } else {
//            model.addAttribute("value", "0");
//        }

        String username = user.getUsername();

        if (user.getUsername().equals("")) {
            List<User> users = userService.selectUserList();
            model.addAttribute("users", users);
        } else {
            model.addAttribute("users", userService.selectUserByUsername(username));
            model.addAttribute("name", username);
        }

        model.addAttribute("username", LoginExitController.username);

//        List<User> users = userService.selectUserByWhere(user);
//        model.addAttribute("users", users);

        return "userList";
    }


    @GetMapping("/userAdd")
    public String userAdd(Model model) {

        String username = LoginExitController.username;
        model.addAttribute("username", username);

        return "userAdd";
    }


    @GetMapping("/checkUserId")
    @ResponseBody
    public String checkUserId(Integer userId) {

        String message = "";
        List<User> users = userService.selectUserList();

        for (User user : users) {
            if (user.getId().equals(userId)) {
                return message = "该编码已存在！请重新输入！";
            } else {
                message = "";
            }
            continue;
        }
        return message;
    }


    @GetMapping("/getUserNewPassword")
    @ResponseBody
    public String getUserNewPassword(String newPassword) {
        new_password = newPassword;
        return new_password;
    }

    @GetMapping("/checkUserReNewPassWord")
    @ResponseBody
    public String checkUserReNewPassWord(String password) {
        String message = "";
        if (new_password.equals(password)) {
            message = "";
        } else {
            message = "新密码与确认密码不一样！请重新输入！";
        }
        return message;
    }


    @GetMapping("/addUser")
    public String addUser(User user, Model model) {

        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encode = encoder.encode(user.getPassword());
        user.setPassword(encode);

        Integer value = user.getValue();

        try {
            userService.insertUser(user);
            if (value.equals(0)) {
                try {
                    userAuthorityService.insertUserAuthority(user.getId(), 1);
                } catch (Exception e) {
                    System.out.println(e.getMessage());

                    return "userAdd";
                }
            } else {
                try {
                    userAuthorityService.insertUserAuthority(user.getId(), 2);
                } catch (Exception e) {
                    System.out.println(e.getMessage());

                    return "userAdd";
                }
            }

        } catch (Exception e) {
            model.addAttribute("error", "添加失败！(user_table)");
            return "userAdd";
        }
        return "redirect:/userList";
    }


    @GetMapping("/userView")
    public String userView(Integer userId, Model model) {
        String username = LoginExitController.username;
        model.addAttribute("username", username);

        User user = userService.selectUserById(userId);
        model.addAttribute("user", user);
        return "userView";
    }


    @GetMapping("/userUpdate")
    public String userUpdate(Integer userId, Model model) {
        String username = LoginExitController.username;
        model.addAttribute("username", username);

        User user = userService.selectUserById(userId);
        model.addAttribute("user", user);
        return "userUpdate";
    }

    @GetMapping("/updateUser")
    public String updateUser(User user, Model model) {

        Integer userAuthorityId = userAuthorityService.getUserAuthorityIdById(user.getId());

        Integer value = user.getValue();

        try {
            userService.updateUser(user);
            if (value.equals(0)) {
                Integer aId = 1;
                try {
                    userAuthorityService.updateUserAuthorityById(aId, userAuthorityId);

                } catch (Exception e) {
                    System.out.println(e.getMessage());

                    return "userUpdate";
                }
            } else {
                Integer aId = 2;
                try {
                    userAuthorityService.updateUserAuthorityById(aId, userAuthorityId);

                } catch (Exception e) {
                    System.out.println(e.getMessage());

                    return "userUpdate";
                }
            }

        } catch (Exception e) {
            model.addAttribute("error", "修改失败！");
            return "userUpdate";
        }

        User updateUser = userService.selectUserById(user.getId());
        model.addAttribute("user", updateUser);

        return "userView";


    }

    @Autowired
    RedisTemplate redisTemplate;

    @GetMapping("/removeUser")
    public String remove(Integer userId, Model model) {

        User user = userService.selectUserById(userId);

        Object o = redisTemplate.opsForValue().get("user");

        ObjectMapper objectMapper = new ObjectMapper();
        User loginUser = objectMapper.convertValue(o, User.class);

        if (user.getId().equals(loginUser.getId())) {
            model.addAttribute("type", "1");
            model.addAttribute("error", "无法删除正在登陆的用户！");

            String username = LoginExitController.username;
            model.addAttribute("username", username);

            List<User> users = userService.selectUserList();
            model.addAttribute("users", users);

            return "userList";
        } else {
            Integer userAuthorityId = userAuthorityService.getUserAuthorityIdById(userId);

            try {
                userAuthorityService.deleteUserAuthorityById(userAuthorityId);

                userService.deleteUserById(userId);

            } catch (Exception e) {

                System.out.println(e.getMessage());

                String message = "删除失败";
                model.addAttribute("message", message);
                model.addAttribute("type", "0");

                String username = LoginExitController.username;
                model.addAttribute("username", username);

                List<User> users = userService.selectUserList();
                model.addAttribute("users", users);

                return "userList";
            }
            return "redirect:/userList";
        }


//        User userById = userService.findById(userId);
//        HttpSession session = request.getSession();
//        User loginUser = (User) session.getAttribute("user");
//        if (userById.equals(loginUser)) {
//            model.addAttribute("type", "1");
//            model.addAttribute("error", "无法删除正在登陆的用户！");
//
//            String username = LoginExitController.username;
//            model.addAttribute("username", username);


//            List<User> users = userService.selectUserByWhere(null);
//            model.addAttribute("users", users);


//            User user = (User) session.getAttribute("user");
//            Integer value = user.getValue();
//            if (value.equals(1)) {
//                model.addAttribute("value", "1");
//            } else {
//                model.addAttribute("value", "0");
//            }
//            return "userList";

//        } else {
//            try {
//                userService.deleteUser(userId);
//            } catch (Exception e) {
//                String message = "删除失败";
//                model.addAttribute("message", message);
//                model.addAttribute("type", "0");
//
//                String username = LoginExitController.username;
//                model.addAttribute("username", username);
//
//
////                List<User> users = userService.selectUserByWhere(null);
////                model.addAttribute("users", users);
//
//
//                User user = (User) session.getAttribute("user");
//
//
//                Integer value = user.getValue();
//                if (value.equals(1)) {
//                    model.addAttribute("value", "1");
//                } else {
//                    model.addAttribute("value", "0");
//                }
//
//                return "userList";
//            }
//            return "redirect:/userList";
//        }

    }


}
